eval(read('/apps/notex.jsx'));
notex.usage('The security session service',
            {username: 'The "security/session" service username',
             password: 'The "security/session" service password',
             session_id: 'Alternatively, provide the session ID',
             remote_addr: '...and the session remote IP address'});

// Setup database options
var options; eval('options=' + read('../options.jsx'));

// Get the username and password
var username = param('username');
var password = param('password');
var session = null;
if (username) {

    // Find the user in the database
    var sql = 'select * from users where username = "' + username + '"';
    var xml = notex.service.sql(sql, options);
    try {
        var user = xml.objects.object;
    } catch (e) {
        cookie('notex_session_id', 'unknown');
        notex.error('No user found with username "' + username + '"');
    }

    // Check that the password matches
    if (user.password != password) {
        cookie('notex_session_id', 'unknown');
        notex.error('Wrong password for user "' + username + '"');
    }

    // Create a new session for the user
    session = notex.session.create(user.id.toString());

} else {

    // Load a session matching the "session_id" and "remote_addr"
    session = notex.session.load();
}

// Write out the user session
if (session && session.data) {
    write(session.toXMLString());
} else {
    cookie('notex_session_id', 'unknown');
    var message = 'No session found ';
    message += username ? 'for username "' + username + '"'
                        : 'with ID "' + notex.session.id + '"';
    notex.error(message);
}

// END
